{% extends 'preheat/base.html' %}

{% block title %}添加服务器 - CDN预热平台{% endblock %}

{% block page_title %}添加服务器{% endblock %}

{% block content %}
<!-- 结果显示区域 -->
<div id="result-container" class="mb-4" style="display: none;">
    <div class="card shadow-sm">
        <div class="card-header bg-light py-3">
            <h3 class="mb-0">提交结果</h3>
        </div>
        <div class="card-body p-4">
            <div id="result-content"></div>
            <div class="d-flex justify-content-end gap-3 mt-4">
                <button id="new-server-btn" class="btn btn-primary px-4">
                    <i class="fas fa-plus me-2"></i>添加新服务器
                </button>
                <a href="{% url 'preheat:server_list' %}" class="btn btn-secondary px-4">
                    <i class="fas fa-list me-2"></i>查看服务器列表
                </a>
            </div>
        </div>
    </div>
</div>

<!-- 表单区域 -->
<div id="form-container" class="card shadow-sm">
    <div class="card-header bg-light py-3">
        <h3 class="mb-0">服务器信息</h3>
    </div>
    <div class="card-body p-4">
        <form id="server-form" method="post" class="needs-validation" novalidate>
            {% csrf_token %}
            <div class="form-group mb-4">
                <label for="id_ip" class="form-label fw-medium">IP地址 <span class="text-danger">*</span></label>
                {{ form.ip }}
                {% if form.ip.errors %}
                <div class="invalid-feedback d-block">
                    {{ form.ip.errors }}
                </div>
                {% else %}
                <div class="form-text text-muted">请输入服务器的IP地址</div>
                {% endif %}
            </div>
            
            <div class="form-group mb-4">
                <label for="id_ssh_port" class="form-label fw-medium">SSH端口 <span class="text-danger">*</span></label>
                {{ form.ssh_port }}
                {% if form.ssh_port.errors %}
                <div class="invalid-feedback d-block">
                    {{ form.ssh_port.errors }}
                </div>
                {% else %}
                <div class="form-text text-muted">默认SSH端口为22</div>
                {% endif %}
            </div>
            
            <div class="form-group mb-4">
                <label for="id_ssh_password" class="form-label fw-medium">SSH密码 <span class="text-danger">*</span></label>
                {{ form.ssh_password }}
                {% if form.ssh_password.errors %}
                <div class="invalid-feedback d-block">
                    {{ form.ssh_password.errors }}
                </div>
                {% else %}
                <div class="form-text text-muted">请输入SSH连接密码</div>
                {% endif %}
            </div>
            
            <div class="form-group mb-4">
                <label for="id_remark" class="form-label fw-medium">服务器归属地域</label>
                {{ form.remark }}
                {% if form.remark.errors %}
                <div class="invalid-feedback d-block">
                    {{ form.remark.errors }}
                </div>
                {% else %}
                <div class="form-text text-muted">可选，添加服务器归属地域信息</div>
                {% endif %}
            </div>
            <div class="d-flex justify-content-end gap-3 mt-4 pt-3 border-top">
                <a href="{% url 'preheat:server_list' %}" class="btn btn-secondary px-4">
                    <i class="fas fa-times me-2"></i>取消
                </a>
                <button type="submit" class="btn btn-primary px-4">
                    <i class="fas fa-save me-2"></i>提交
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
    /* 表单验证反馈样式 */
    .invalid-feedback {
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }
    
    /* 表单帮助文本样式 */
    .form-text {
        font-size: 0.8rem;
        margin-top: 0.25rem;
    }
    
    /* 必填字段标记样式 */
    .text-danger {
        font-weight: bold;
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 表单验证
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                // 获取所有需要验证的表单
                var forms = document.getElementsByClassName('needs-validation');
                
                // 循环遍历并阻止提交
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        } else {
                            // 表单验证通过，使用AJAX提交
                            event.preventDefault();
                            submitForm();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
        
        // 表单提交函数
        function submitForm() {
            var form = $('#server-form');
            var formData = form.serialize();
            var submitBtn = form.find('button[type="submit"]');
            var originalBtnText = submitBtn.html();
            
            // 禁用提交按钮并显示加载状态
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>提交中...');
            
            // 发送AJAX请求
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // 显示成功结果
                        showResult(true, response.message, response.data);
                    } else {
                        // 显示错误结果
                        showResult(false, response.message, response.errors);
                    }
                },
                error: function(xhr) {
                    // 处理AJAX错误
                    var errorMessage = '请求失败，请稍后重试';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                    showResult(false, errorMessage);
                },
                complete: function() {
                    // 恢复提交按钮状态
                    submitBtn.prop('disabled', false).html(originalBtnText);
                }
            });
        }
        
        // 显示结果函数
        function showResult(success, message, data) {
            var resultContainer = $('#result-container');
            var resultContent = $('#result-content');
            var formContainer = $('#form-container');
            
            // 清空之前的结果
            resultContent.empty();
            
            // 根据结果显示不同的内容
            if (success) {
                // 成功结果
                var resultHtml = '<div class="alert alert-success d-flex align-items-center" role="alert">';
                resultHtml += '<i class="fas fa-check-circle me-2"></i>';
                resultHtml += '<div>' + message + '</div>';
                resultHtml += '</div>';
                
                // 如果有数据，显示数据详情
                if (data) {
                    resultHtml += '<div class="mt-4">';
                    resultHtml += '<h5>服务器详情：</h5>';
                    resultHtml += '<table class="table table-bordered">';
                    resultHtml += '<tbody>';
                    resultHtml += '<tr><th style="width: 150px;">IP地址</th><td>' + (data.ip || '') + '</td></tr>';
                    resultHtml += '<tr><th>SSH端口</th><td>' + (data.ssh_port || '') + '</td></tr>';
                    resultHtml += '<tr><th>备注</th><td>' + (data.remark || '') + '</td></tr>';
                    resultHtml += '<tr><th>创建时间</th><td>' + (data.created_time || '') + '</td></tr>';
                    resultHtml += '</tbody>';
                    resultHtml += '</table>';
                    resultHtml += '</div>';
                }
            } else {
                // 错误结果
                var resultHtml = '<div class="alert alert-danger d-flex align-items-center" role="alert">';
                resultHtml += '<i class="fas fa-exclamation-circle me-2"></i>';
                resultHtml += '<div>' + message + '</div>';
                resultHtml += '</div>';
                
                // 如果有错误详情，显示错误详情
                if (data && typeof data === 'object') {
                    resultHtml += '<div class="mt-4">';
                    resultHtml += '<h5>错误详情：</h5>';
                    resultHtml += '<ul class="list-group">';
                    
                    for (var field in data) {
                        if (data.hasOwnProperty(field)) {
                            resultHtml += '<li class="list-group-item">';
                            resultHtml += '<strong>' + field + ':</strong> ' + data[field];
                            resultHtml += '</li>';
                        }
                    }
                    
                    resultHtml += '</ul>';
                    resultHtml += '</div>';
                }
            }
            
            // 设置结果内容
            resultContent.html(resultHtml);
            
            // 显示结果容器，隐藏表单容器
            resultContainer.show();
            formContainer.hide();
            
            // 滚动到结果区域
            $('html, body').animate({
                scrollTop: resultContainer.offset().top - 20
            }, 500);
        }
        
        // 添加新服务器按钮点击事件
        $('#new-server-btn').on('click', function() {
            // 重置表单
            $('#server-form')[0].reset();
            $('#server-form').removeClass('was-validated');
            
            // 清除所有验证状态
            $('.form-control').removeClass('is-valid is-invalid');
            $('.invalid-feedback').removeClass('d-block');
            
            // 显示表单容器，隐藏结果容器
            $('#form-container').show();
            $('#result-container').hide();
            
            // 滚动到表单区域
            $('html, body').animate({
                scrollTop: $('#form-container').offset().top - 20
            }, 500);
        });
    });
</script>
{% endblock %}